"use strict";

const { vec3 } = glMatrix;

var gl;
var points;

var numPoints = 5000;

window.onload = function initPoints(){
	var canvas = document.getElementById( "gl-canvas" );

	gl = WebGLUtils.setupWebGL( canvas );
	if( !gl ){
		alert( "WebGL isn't available" );
	}

	//渲染顶点的坐标
	var vertices = [
		-1, -1,  0, //u1
		 0,  1,  0, //u2
		 1, -1,  0 //u3
	];

	var u1 = vec3.fromValues( vertices[0], vertices[1], vertices[2] );
	var u2 = vec3.fromValues( vertices[3], vertices[4], vertices[5] );
	var u3 = vec3.fromValues( vertices[6], vertices[7], vertices[8] );

// 创建一个可在WebGL内部使用的vec3对象；如果指定了参数a，则使用a的数据初始化新创建的对象
	var u = vec3.create();
//计算u1+u2的值，如果指定了u，则保存在u
	vec3.add( u, u1, u2);
	var v = vec3.create();
	vec3.add( v, u1, u3);

	var p = vec3.create();
	vec3.add( p, u, v );
	vec3.scale( p, p, 0.25 );
	
	points = [];
	for( var i = 0; i < 3; i++ )
		points.push( p[i] );

	for( var i = 0; points.length < numPoints * 3; i++ ){
		var j = Math.floor( Math.random() * 3 );
		// jth from vertices
		
		vec3.set( u, vertices[j*3], vertices[j*3+1], vertices[j*3+2] );
		vec3.set( v, points[i*3], points[i*3+1], points[i*3+2]);
		
		vec3.add( p, u, v );
		vec3.scale( p, p, 0.5 );
		
		for( var k = 0; k < 3; k++ )
			points.push( p[ k ] );
	}
	
	//console是在浏览器控制台中打印出plen的数值
	console.log( "plen:"+points.length ); 
	// Configure WebGL
	gl.viewport( 0, 0, canvas.width, canvas.height );
	gl.clearColor( 1.0, 1.0, 1.0, 1.0 );

	// load shaders and initialize attribute buffers
	var program = initShaders( gl, "vertex-shader", "fragment-shader" );
	gl.useProgram( program );

	// load data into the gpu
	var bufferId = gl.createBuffer();
	gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
	gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( points ), gl.STATIC_DRAW );

	// associate external shader variables with data buffer 
	var vPosition = gl.getAttribLocation( program, 'vPosition' );
	gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
	gl.enableVertexAttribArray( vPosition );

	renderPoints();
};

function renderPoints(){
	gl.clear( gl.COLOR_BUFFER_BIT );
	gl.drawArrays( gl.POINTS, 0, numPoints );
}